<template>
  <el-dialog  center :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" >
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px" >
      <el-form-item prop="account" :label="$t('user.account')" :dept-name.sync="dataForm.account">
        <el-input v-model="dataForm.account" :placeholder="$t('user.account')"></el-input>
      </el-form-item>
	  <el-form-item prop="username" :label="$t('user.username')">
        <el-input v-model="dataForm.username" :placeholder="$t('user.username')"></el-input>
      </el-form-item>
      <el-form-item prop="deptName" :label="$t('user.deptName')">
			<ren-dept-tree  v-model="dataForm.deptId" :placeholder="$t('dept.title')" :dept-name.sync="dataForm.deptName"></ren-dept-tree>
      </el-form-item>
      <el-form-item v-if="!modifyExtendsParam.id" prop="password" :label="$t('user.password')" :class="{ 'is-required': !dataForm.id }">
        <el-input  autocomplete="new-password"  v-model="dataForm.password" type="password" :placeholder="$t('user.password')"></el-input>
      </el-form-item>
      <el-form-item v-if="!modifyExtendsParam.id" prop="confirmPassword" :label="$t('user.confirmPassword')" :class="{ 'is-required': !dataForm.id }">
        <el-input autocomplete="new-password" v-model="dataForm.confirmPassword" type="password" :placeholder="$t('user.confirmPassword')"></el-input>
      </el-form-item>
      <el-form-item prop="phone" :label="$t('phone')">
        <el-input v-model="dataForm.phone" :placeholder="$t('phone')"></el-input>
      </el-form-item>
      <el-form-item prop="roleId" :label="$t('user.roleIdList')" class="role-list">
        <el-select v-model="dataForm.roleId" multiple :placeholder="$t('user.roleIdList')">
          <el-option v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
	  <el-form-item prop="postId" :label="$t('user.postId')" class="role-list">
	    <el-select v-model="dataForm.postId"  :placeholder="$t('user.postId')">
	      <el-option v-for="item in postList" :key="item.postId" :label="'('+item.postCode+')  ' + item.postName" :value="item.postId"></el-option>
	    </el-select>
	  </el-form-item>
	  <el-form-item prop="memo" :label="$t('remark')">
	    <el-input v-model="dataForm.memo" :placeholder="$t('remark')"></el-input>
	  </el-form-item>
      <el-form-item prop="status" :label="$t('status')" size="mini">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">{{ $t('status1') }}</el-radio>
          <el-radio :label="0">{{ $t('status0') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import {  isMobile } from '@/utils/validate'
import { setMd5 } from '@/utils'
export default {
  data () {
    return {
      visible: false,
	  modifyExtendsParam: {},
	  extendsParam: {},
      roleList: [],
	  postList: [],
      dataForm: {
        id: '',
        username: '',
        deptId: '',
		postId: '',
        deptName: '',
        password: '',
        confirmPassword: '',
        account: '',
        memo: '',
        phone: '',
        roleIdList: [],
		roleId: [],
        status: 1
      }
    }
  },
  computed: {
    dataRule () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t('user.validate.confirmPassword')))
        }
        callback()
      }
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(new Error(this.$t('validate.format', { 'attr': this.$t('user.mobile') })))
        }
        callback()
      }
	  
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        phone: [
          { validator: validateMobile, trigger: 'blur' }
        ],
		account: [
		  { required: true, message: this.$t('validate.required'), trigger: 'change' }
		]
      }
    }
  },
  methods: {
    init () {
	  this.dataForm.id = this.modifyExtendsParam.id;
      this.visible = true
      this.dataForm.deptId = ''
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        Promise.all([
          this.getRoleList(),
		  this.getPostList()
        ]).then(() => {
          if (this.dataForm.id) {
			  this.dataForm.password = '';
			  this.dataForm.confirmPassword = '';
				this.getInfo()
          }
        })
      })
    },
    // 获取角色列表
    getRoleList () {
      return this.$http.get('/pc/role/list').then(({ data: res }) => {
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        this.roleList = res.rows
      }).catch(() => {})
    },
	getPostList () {
		var params = {
			pageNo:1,
			pageSize: 999999
		}
	  return this.$http.get('/pc/post/page',params).then(({ data: res }) => {
	    if (res.code !== 200) {
	      return this.$message.error(res.msg)
	    }
	    this.postList = res.rows
	  }).catch(() => {})
	},
    // 获取信息
    getInfo () {
      
        this.dataForm = {
          ...this.dataForm,
          ...this.modifyExtendsParam,
          roleIdList: []
        }
        // 角色配置, 区分是否为默认角色
        // for (var i = 0; i < ttRoleList.length; i++) {
        //   if (this.roleList.filter(item => item.id === ttRoleList[i])) {
        //     this.dataForm.roleIdList.push(ttRoleList[i])
        //     continue
        //   }
          this.dataForm.roleId = [this.modifyExtendsParam.roleId]
        // }
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
		
		var url = !this.dataForm.id ? '/pc/systemUser/add' : '/pc/systemUser/modify';
		var pwd = this.dataForm.password;
		if(!this.dataForm.id){
			this.dataForm.password = setMd5(pwd);
		}else{
			this.dataForm.password = null;
		}
		
        this.$http['post'](url, {
          ...this.dataForm,
          roleIdList: [
            ...this.dataForm.roleIdList
          ]
        }).then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
